package com.rivulet.doj_backend.tools;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public final class JvmCacheUtil {

    public static final String JVM_CACHE_SPECIFY_GEO = "cache_specify_geo";

    public static final String JVM_CACHE_BUILD_SQL = "cache_build_sql";

    public static final int DEFAULT_CAPACITY = 50;

    public static final long DEFAULT_CACHE_EXP = 12L;

    public static final long DEFAULT_CACHE_ENTRY_EXP = 900L;
    /**
     * 12小时后过期
     */
    private static Cache<String,
            Cache> cacheManager = CacheBuilder.newBuilder()
            .maximumSize(DEFAULT_CAPACITY)
            .expireAfterAccess(12L, TimeUnit.HOURS)
            .expireAfterWrite(12L, TimeUnit.HOURS)
            .initialCapacity(10)
            .build();

    public static Cache getCache(String cacheName) {
        return getCache(cacheName, DEFAULT_CAPACITY, DEFAULT_CACHE_ENTRY_EXP, TimeUnit.SECONDS);
    }

    public static Cache getCache(String cacheName, long expire, TimeUnit timeUnit) {
        return getCache(cacheName, DEFAULT_CAPACITY, expire, timeUnit);
    }

    public static Cache getCache(String cacheName, int capacity, long expire, TimeUnit timeUnit) {
        Cache cache = cacheManager.getIfPresent(cacheName);
        if (null == cache) {
            cache = CacheBuilder.newBuilder()
                    .maximumSize(DEFAULT_CAPACITY)
                    .expireAfterAccess(expire, timeUnit)
                    .expireAfterWrite(expire, timeUnit)
                    .initialCapacity(capacity)
                    .build();
            cacheManager.put(cacheName, cache);
        }
        return cache;
    }

    public static Object get(String cacheName, String key) {
        Cache cache = getCache(cacheName);
        return cache.getIfPresent(key);
    }

    public static void put(String cacheName, String key, Object val) {
        Cache cache = getCache(cacheName);
        cache.put(key, val);
    }

    public static void put(String cacheName, String key, Object val, long expire, TimeUnit timeUnit) {
        Cache cache = getCache(cacheName, expire, timeUnit);
        cache.put(key, val);
    }
}